<template>
  <div>
    <div class="main-wrap">
      <!-- 表单 -->
      <el-form :inline="true" :model="ruleForm" ref="ruleForm" size="small" label-width="auto" class="search-form">

        <!-- 姓名 -->

        <div class="input-wrap">
          <el-form-item label="姓名：" prop="name">
            <el-input v-model="ruleForm.name" placeholder="请输入姓名"></el-input>
          </el-form-item>

          <el-form-item label="账号：" prop="account">
            <el-input v-model="ruleForm.account" placeholder="请输入账号"></el-input>
          </el-form-item>

          <el-form-item label="负责人：" prop="person">
            <el-input v-model="ruleForm.person" placeholder="请输入负责人"></el-input>
          </el-form-item>
        </div>

        <div class="animate-search"
             :class="[moreSearchVisible?'show-animate':'hide-animate']">
          <div class="input-wrap">
            <el-form-item label="角色：" prop="role">
              <el-input v-model="ruleForm.role" placeholder="请输入角色"></el-input>
            </el-form-item>

            <el-form-item label="科室：" prop="deptCode">
              <el-cascader
                  popperClass="option-list"
                  @focus="getDepartmentOptions()"
                  ref="refHandle"
                  placeholder="请选择科室"
                  v-model="ruleForm.deptCode"
                  :options="departmentOptions"
                  :props="{ checkStrictly: true }"
                  :show-all-levels="false"
                  :key="key"
              ></el-cascader>
            </el-form-item>

            <el-form-item label="日期：">
              <el-date-picker type="date" placeholder="选择日期" v-model="ruleForm.time"
                              style="width: 100%;"></el-date-picker>
            </el-form-item>
          </div>

          <div class="input-wrap">
            <el-form-item label="ID：" prop="id">
              <el-input v-model="ruleForm.id" placeholder="请输入ID"></el-input>
            </el-form-item>
          </div>

        </div>

        <div class="show-more-search not-select" @click="moreSearchVisible=!moreSearchVisible">
          <p>{{ moreSearchVisible?'收起':'展开' }}</p>
        </div>

      </el-form>

      <div class="button-groups">
        <!-- 左边放这 -->
        <div class="left-groups">
          <a-button type="primary" @click="addPerson">
            <i class="iconfont iconplus mr5"></i>
            新增
          </a-button>
          <a-button>导出</a-button>
          <a-button>删除</a-button>
        </div>

        <!-- 右边放这 -->
        <div class="right-groups">
          <a-button class="search-btn" type="primary" @click="setIsSearchTrue(),getTable()">
            <i class="iconfont iconsearch"></i>
          </a-button>
          <a-button class="search-btn" @click="setIsSearchFalse(),resetSearchForm('ruleForm')">
            <i class="iconfont iconsync"></i>
          </a-button>
        </div>

      </div>

      <!-- 导入 -->
      <a-modal
          :dialogClass="'common-modal'"
          :width="588"
          :maskClosable="false"
          centered
          v-model="importRecordVisible"
          title="导入人员信息"
          okText="提交"
          cancelText="取消"
          @ok="importRecordConfirm()"
          @cancel="importRecordCancel()">

        <el-upload
            :action="uploadUrl()"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :before-upload="beforeUpload"
            multiple
            ref="upload"
            :limit="1"
            :on-exceed="handleExceed"
            :on-success="handleSuccess"
            :file-list="fileList"
            :auto-upload="false"
        >
          <span><i style="color:rgba(221,0,0,1)">*</i>导入文件：</span>
          <a-button><i class="iconfont iconupload"></i>上传文件</a-button>
          <div slot="tip" class="el-upload__tip" style="padding-left: 77px;font-size: 14px;">
            只支持excel格式文件，文件大小需小于15M。
          </div>
        </el-upload>
        <a-button type="link" style="display: block;padding-left: 80px  ">
          <a href="javascript:void(0);"
             @click="exportExcel('downloadTemp')"
             ref="downloadTemp"
          >下载模板</a>
        </a-button>

      </a-modal>

      <!-- 添加 / 编辑  弹窗 -->
      <a-modal
          :dialogClass="'common-modal'"
          :width="588"
          :maskClosable="false"
          centered
          v-model="addPersonVisible"
          :title="getTitle"
          okText="提交"
          cancelText="取消"
          @ok="addPersonConfirm('addPersonForm')"
          @cancel="addPersonCancel('addPersonForm')">

        <!-- 表单 -->
        <el-form class="warn-form" :inline="true" :model="addPersonForm" :rules="addPersonRules" ref="addPersonForm"
                 size="small" label-width="100px">

          <!-- 科室 -->
          <el-form-item label="科室：" prop="deptCode">
            <el-cascader
                popperClass="option-list"
                @focus="getDepartmentOptions('add')"
                ref="refHandle"
                placeholder="请选择科室"
                v-model="addPersonForm.deptCode"
                :options="addDepartmentOptions"
                :props="{ checkStrictly: true }"
                :key="key"
            ></el-cascader>
          </el-form-item>

          <!-- 姓名 -->
          <el-form-item label="姓名：" prop="name">
            <el-input v-model.trim="addPersonForm.name" placeholder="请输入姓名" maxlength="35"></el-input>
          </el-form-item>

          <!-- 医院名称 -->
          <el-form-item label="医院名称：" prop="hospital">
            <el-input v-model.trim="addPersonForm.hospital" placeholder="请输入医院名称" maxlength="35"></el-input>
          </el-form-item>

          <!-- QrCode -->
          <el-form-item label="QrCode：" prop="code">
            <el-input v-model="addPersonForm.code" placeholder="请输入QrCode" maxlength="18"></el-input>
          </el-form-item>

          <!-- 职称 -->
          <el-form-item label="职称：" prop="title">
            <el-input v-model="addPersonForm.title" placeholder="请输入职称" maxlength="35"></el-input>
          </el-form-item>

          <!-- 职位 -->
          <el-form-item label="职位：" prop="position">
            <el-input v-model="addPersonForm.position" placeholder="请输入职位" maxlength="35"></el-input>
          </el-form-item>

          <!-- 职务 -->
          <el-form-item label="职务：" prop="job">
            <el-input v-model="addPersonForm.job" placeholder="请输入职务" maxlength="35"></el-input>
          </el-form-item>

          <!-- 工号 -->
          <el-form-item label="工号：" prop="jobNumber">
            <el-input v-model="addPersonForm.jobNumber" placeholder="请输入工号" maxlength="18"></el-input>
          </el-form-item>

        </el-form>

      </a-modal>

      <!-- 表格 -->
      <el-table
          id="out-table"
          v-loading="tableLoading"
          class="table"
          ref="multipleTable"
          :data="newTableData"
          tooltip-effect="dark"
          style="width: 100%"
          :row-key="getRowKey"
          @row-click="clickRow"
          @selection-change="changeStatus($event)"
          empty-text="暂无数据"
          height="30vh"
          :cell-class-name="getCellName">

        <el-table-column type="selection" width="55" :reserve-selection="true"
                         :selectable='selectInit'></el-table-column>
        <el-table-column type="index" label="序号" :index="index" width="106"></el-table-column>
        <el-table-column prop="account" label="账号" width="" show-overflow-tooltip></el-table-column>
        <el-table-column prop="role" label="角色" width="" show-overflow-tooltip></el-table-column>
        <el-table-column prop="area" label="使用病区" width="" show-overflow-tooltip></el-table-column>
        <el-table-column prop="person" label="负责人" width="" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" width="150">
          <template slot-scope="scope" v-if="scope.row.length!==0">
            <a-button class="p0" type="link" @click.stop="editPerson(scope.row)">
              编辑
            </a-button>

            <el-divider direction="vertical"></el-divider>

            <a-button class="p0" type="link" @click.stop="deletePerson(scope.row)">
              删除
            </a-button>

            <el-divider direction="vertical"></el-divider>

            <a-button class="p0" type="link" @click.stop="deletePerson(scope.row)">
              删除
            </a-button>

          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes=pageSizes
          :page-size=pageSize
          :total=total
          :current-page.sync="currentPage"
          prev-text="上一页"
          next-text="下一页"
          layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>

    </div>
  </div>
</template>

<script>
import { modalMixin, commonMixin, deptMixin, pageMixin } from '@/mixins/commonMixin';
import Bread from '@/components/bread/bread';

import { Modal } from 'ant-design-vue';

import base from '@/api/base';

const prod = base.prod;

export default {
  name: 'Person',

  mixins: [commonMixin, modalMixin, deptMixin, pageMixin],

  components: {
    Bread,
  },

  watch: {
    checkAddName: async function(newVal, oldVal) {
      let canCheck = Object.values(newVal).every(item => {
        // console.log(item);
        return item;
      });
      // console.log(canCheck);
      if (canCheck) {
        this.onlyCheck('name');
      }
    }
  },

  computed: {
    ids() {
      let t = _.cloneDeep(this.isCheckedList);
      let ids = [];
      t.forEach(item => {
        ids.push(item.serialId);
      });
      // console.log(ids)
      return ids;
    },
    checkAddName() {
      return {
        name: this.addPersonForm.name,
        productKey: this.addPersonForm.deptCode && (this.addPersonForm.deptCode[this.addPersonForm.deptCode.length - 1])
      };
    }
  },

  data() {
    const validateName = async(rule, value, cb) => {
      const res = this.isRepeatName;
      if (res) {
        cb(new Error('已有该姓名，请重新输入...'));
      } else {
        cb();
      }
    };

    const validateJobNumber = async(rule, value, cb) => {
      const res = await this.sendCheck('isRepeatJobNumber', 'jobNumber');
      if (res) {
        cb(new Error('已有该工号，请重新输入...'));
      } else {
        cb();
      }
    };

    return {
      // 表单数据
      ruleForm: {
        name: '',
        account: '',
        person: '',
        role: '',
        deptCode: [''],
        time: '',
        id: '',
      },

      // 是否展示更多搜索条件
      moreSearchVisible: false,

      tableData: [{
        id: 1,
        account: '演示的账号',
        role: '角色',
        area: '病区',
        person: '负责人'
      },
        {
          id: 2,
          account: '演示的账号2',
          role: '角色2',
          area: '病区2',
          person: '负责人2'
        }],

      // 导入弹窗显示
      importRecordVisible: false,

      // 上传文件列表
      fileList: [],

      // 文件大小判断 需要小于15M 1为符合标准 0为不合标准
      fileSize: 0,

      // 添加 / 编辑人员
      getTitle: '',

      // 添加人员弹窗显示
      addPersonVisible: false,

      // 添加人员表单
      addPersonForm: {
        deptCode: [],
        name: '',
        hospital: '',
        code: '',
        title: '',
        position: '',
        job: '',
        jobNumber: '',
      },

      // 添加人员表单验证
      addPersonRules: {
        deptCode: [
          { required: true, message: '请选择科室', trigger: 'blur' },
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' },
          { validator: validateName, trigger: 'blur' }
        ],
        hospital: [
          { required: true, message: '请输入医院名称', trigger: 'blur' },
        ],
        jobNumber: [
          { validator: validateJobNumber, trigger: 'blur' }
        ]
      },

      // 是否有重复名称
      isRepeatName: false,

      // 是否有重复卡号
      isRepeatJobNumber: false,

      // 当前编辑的行
      row: {},

    };
  },

  created() {
    // this.getTable();
  },

  mounted() {

    setInterval(function() {
      document.querySelectorAll('.el-cascader-node__label').forEach(el => {
        el.onclick = function() {
          if (this.previousElementSibling) this.previousElementSibling.click();
        };
      });
    }, 1000);
  },

  methods: {
    uploadUrl() {
      return `${prod}/staffDict/importExcel`;
    },

    // 获取参数
    getParam() {
      let param = _.cloneDeep(this.ruleForm);
      param.deptCode = param.deptCode[param.deptCode.length - 1];
      return param;
    },

    // 获取表格
    async getTable(pageNum = 1) {
      try {

        this.tableLoading = true;

        let param;
        if (this.isSearch) {
          param = this.getParam();
        }

        const res = await this.$api.basics.getPersonTableData({
          // 科室
          ...param,
          pageNum,
          pageSize: 15
        });
        // console.log(res);
        if (res.data.type === 'success') {
          this.tableData = res.data.data.list;
          this.total = res.data.data.total;
          this.clearTable('multipleTable');
          this.tableLoading = false;
          this.clearTable();
        } else {
          throw new Error('系统返回错误');
        }
      } catch (e) {
        this.tableData = [];
        this.tableLoading = false;
      }
    },

    // 重置搜索表单
    resetSearchForm(formName) {
      this.resetForm(formName);
      this.currentPage = 1;
      this.getTable();
      this.clearTable('multipleTable');
      this.key++;
    },

    // 添加人员
    addPerson() {
      this.getTitle = '添加人员信息';
      this.addPersonVisible = true;
    },

    // 编辑人员
    editPerson(row) {
      this.getDepartmentOptions();
      this.getTitle = '编辑人员信息';
      this.row = row;
      this.addPersonVisible = true;
      let { code, hospital, deptCode, job, jobNumber, name, position, title } = row;

      deptCode ? (deptCode = this.tools.getDeptArray(deptCode)) : [];

      this.addPersonForm = Object.assign({}, { code, hospital, job, deptCode, jobNumber, name, position, title });


      this.$nextTick(() => {
        this.$refs.addPersonForm && this.$refs.addPersonForm.clearValidate();
      });

    },

    // 唯一检验
    onlyCheck(type) {
      // console.log(type);
      // 如果输入框的值不为空，向后台发送验证
      this.$refs.addPersonForm && this.$refs.addPersonForm.validateField(type, err => {
        switch (type) {
        case 'name':
          if (err === '' || err !== '请输入姓名') {
            this.sendCheck('isRepeatName', type);
          }
          break;
        case 'jobNumber':
          this.sendCheck('isRepeatJobNumber', type);
          break;
        }
      });
    },

    async sendCheck(variable, type) {
      if (this.addPersonForm[type] === '') {
        return;
      }
      let param = {};
      switch (type) {
      case 'name':
        param.name = this.addPersonForm[type];
        param.deptCode = this.addPersonForm.deptCode[this.addPersonForm.deptCode.length - 1];
        break;
      case 'jobNumber':
        param.jobNumber = this.addPersonForm[type];
        break;
      }
      // 发送请求
      const res = await this.$api.basics.getPersonOne({
        ...param
      });

      // console.log(res.data.data);
      if (res.data.type !== 'success') {
        throw new Error('系统返回错误');
      }
      if (res.data.data) {
        // 如果有信息，则判断是否是编辑，并且编辑项与当前相同
        if (this.getTitle === '编辑人员信息') {
          this[variable] = this.row.id !== res.data.data.id;
        } else {
          this[variable] = true;
        }
      } else {
        this[variable] = false;
      }

      if (type === 'name') {
        this.$refs.addPersonForm.validateField(type);
        return;
      }

      return this[variable];

    },

    // 添加 / 编辑人员确定
    addPersonConfirm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.getTitle === '添加人员信息') {
            this.addPersonHandle();
          } else if (this.getTitle === '编辑人员信息') {
            this.editPersonHandle();
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    // 添加操作
    async addPersonHandle() {
      let { addPersonForm: param } = this;
      param.deptCode = param.deptCode[param.deptCode.length - 1];

      const res = await this.$api.basics.getPersonAdd({
        ...this.addPersonForm
      });

      console.log(res);
      if (res.data.type === 'success') {
        this.getTable(this.currentPage);
        this.clearTable();
        this.addPersonCancel('addPersonForm');
      } else {
        this.$message.error(res.data.msg);
      }

    },

    // 编辑操作
    async editPersonHandle() {
      let param = _.cloneDeep(this.addPersonForm);
      param.deptCode = param.deptCode[param.deptCode.length - 1];
      // 添加id
      param.id = this.row.id;
      // param.serialId = this.row.serialId;
      console.log(param);
      const res = await this.$api.basics.getPersonEdit({
        ...param
      });
      // console.log(res);
      if (res.data.type === 'success') {
        this.getTable(this.currentPage);
        this.addPersonVisible = false;
        this.$message.success('编辑成功');
      } else {
        this.$message.error(res.data.msg);
      }
    },

    // 添加 / 编辑人员取消
    addPersonCancel(formName) {
      this.$nextTick(() => {
        this.addPersonForm = Object.assign({}, {
          deptCode: [],
          name: '',
          hospital: '',
          code: '',
          title: '',
          position: '',
          job: '',
          jobNumber: '',
        });
        this.isRepeatName = this.isRepeatName = false;
        this.clearForm(formName);
        this.addPersonVisible = false;

        this.key++;

      });
    },

    // 删除人员
    deletePerson(row) {
      this.$modal({
        title: '删除温馨提示？',
        content: `请确认内容，确定要删除 ${row.account} 吗？`,
        confirmHandle: async() => {
          const res = await this.$api.basics.getPersonDelete(this.ids);
          console.log(res);
          if (res.data.type === 'success') {
            this.$message.success('删除成功');
            this.afterDelete(res);
          } else {
            this.$message.error('删除失败');
          }
        },
      });
    },

    // 同步
    syncRecord() {
      this.$modal({
        title: '提示',
        content: '尚未对接HIS系统，同步功能不可用！',
      });
    },

    // 导入
    importRecord() {
      this.importRecordVisible = true;
    },

    // 导入确定
    importRecordConfirm() {
      // 上传文件
      this.$refs.upload.submit();
    },

    // 导入取消
    importRecordCancel() {
      this.uploadShow = false;
      this.$nextTick(() => {
        this.$refs.upload.clearFiles();
      });
    },

    // 上传下载模板
    // 导出excel
    exportExcel(linkRef) {
      let path = '/staffDict/downloadExcel';

      // this.$refs[linkRef].href = `${prod}${path}${arg}`;
      this.$refs[linkRef].href = `${prod}${path}`;

      this.$message.success('文件下载中，请查看浏览器的下载中心');
    },

    // 上传
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      // 自动过滤大小不符合标准的文件
      if (this.fileSize === 0) {
        return true;
      } else {
        return this.$confirm({
          centered: true,
          content: `确定移除 ${file.name}`,
          okText: '确定',
          cancelText: '取消',
          onOk: () => {
            this.uploadErrList = [];
          },
        });
      }
    },
    // 上传前
    beforeUpload(file) {
      console.log(file);

      // 文件类型限制
      let fileType = file.name.replace(/.+\./, '');
      console.log(fileType);
      if (fileType !== 'xls' && fileType !== 'xlsx') {
        this.$message.warning('仅支持excel文件');
        return false;
      }
      // 文件大小显示 1 符合标准      0 不合标准
      this.fileSize = file.size / 1024 < 15 * 1024 ? 1 : 0;
      // console.log(this.fileSize)
      if (this.fileSize === 0) {
        this.$message.warning('文件需小于15M');
        return false;
      }
    },
    handleSuccess(res, file, fileList) {
      console.log(res);

      if (res.type === 'success') {
        // 关闭弹窗
        this.importRecordVisible = false;
        // 刷新列表
        this.getTable(this.currentPage);
        this.$nextTick(() => {
          this.$refs.upload.clearFiles();
        });
        this.$message.success('导入成功');
      } else {
        this.uploadErrList = [];
        this.$message.warn('导入失败，请刷新重试');
        console.log(res);
        let errData = res.data;
        // 处理错误信息
        for (let k in errData) {
          if (errData.hasOwnProperty(k)) {
            let position = k.split(',');
            console.log(position);
            this.uploadErrList.push({
              column: position[0],
              line: position[1],
              tip: errData[k]
            });
          }
        }
      }
    },

  },

};
</script>
